{% extends "layout.html" %}

{% block title %}任务管理 - 金融数据平台{% endblock %}

{% block content %}
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h4 class="mb-0"><i class="fas fa-tasks me-2"></i>任务管理</h4>
                <button class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#newTaskModal">
                    <i class="fas fa-plus me-1"></i>新建任务
                </button>
            </div>
            <div class="card-body">
                <ul class="nav nav-tabs" id="taskTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="all-tab" data-bs-toggle="tab" data-bs-target="#all" type="button" role="tab" aria-controls="all" aria-selected="true">
                            <i class="fas fa-list me-1"></i>所有任务
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="running-tab" data-bs-toggle="tab" data-bs-target="#running" type="button" role="tab" aria-controls="running" aria-selected="false">
                            <i class="fas fa-spinner me-1"></i>运行中
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="completed-tab" data-bs-toggle="tab" data-bs-target="#completed" type="button" role="tab" aria-controls="completed" aria-selected="false">
                            <i class="fas fa-check-circle me-1"></i>已完成
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="failed-tab" data-bs-toggle="tab" data-bs-target="#failed" type="button" role="tab" aria-controls="failed" aria-selected="false">
                            <i class="fas fa-times-circle me-1"></i>失败
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="scheduled-tab" data-bs-toggle="tab" data-bs-target="#scheduled" type="button" role="tab" aria-controls="scheduled" aria-selected="false">
                            <i class="fas fa-clock me-1"></i>计划任务
                        </button>
                    </li>
                </ul>
                <div class="tab-content p-3" id="taskTabsContent">
                    <div class="tab-pane fade show active" id="all" role="tabpanel" aria-labelledby="all-tab">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>任务类型</th>
                                        <th>证券代码</th>
                                        <th>开始日期</th>
                                        <th>结束日期</th>
                                        <th>状态</th>
                                        <th>结果数量</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="allTasksTable">
                                    <!-- 任务数据将通过JavaScript加载 -->
                                    <tr>
                                        <td colspan="9" class="text-center">加载中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <nav aria-label="任务分页">
                            <ul class="pagination justify-content-center">
                                <li class="page-item disabled">
                                    <a class="page-link" href="#" tabindex="-1">上一页</a>
                                </li>
                                <li class="page-item active"><a class="page-link" href="#">1</a></li>
                                <li class="page-item"><a class="page-link" href="#">2</a></li>
                                <li class="page-item"><a class="page-link" href="#">3</a></li>
                                <li class="page-item">
                                    <a class="page-link" href="#">下一页</a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                    <div class="tab-pane fade" id="running" role="tabpanel" aria-labelledby="running-tab">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>任务类型</th>
                                        <th>证券代码</th>
                                        <th>进度</th>
                                        <th>开始时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="runningTasksTable">
                                    <!-- 运行中任务数据将通过JavaScript加载 -->
                                    <tr>
                                        <td colspan="6" class="text-center">加载中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="completed" role="tabpanel" aria-labelledby="completed-tab">
                        <!-- 已完成任务表格，类似于上面的结构 -->
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>任务类型</th>
                                        <th>证券代码</th>
                                        <th>结果数量</th>
                                        <th>完成时间</th>
                                        <th>耗时</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="completedTasksTable">
                                    <!-- 已完成任务数据将通过JavaScript加载 -->
                                    <tr>
                                        <td colspan="7" class="text-center">加载中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <nav aria-label="完成任务分页">
                            <ul class="pagination justify-content-center">
                                <li class="page-item disabled">
                                    <a class="page-link" href="#" tabindex="-1">上一页</a>
                                </li>
                                <li class="page-item active"><a class="page-link" href="#">1</a></li>
                                <li class="page-item"><a class="page-link" href="#">2</a></li>
                                <li class="page-item"><a class="page-link" href="#">3</a></li>
                                <li class="page-item">
                                    <a class="page-link" href="#">下一页</a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                    <div class="tab-pane fade" id="failed" role="tabpanel" aria-labelledby="failed-tab">
                        <!-- 失败任务表格，类似于上面的结构 -->
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>任务类型</th>
                                        <th>证券代码</th>
                                        <th>失败原因</th>
                                        <th>重试次数</th>
                                        <th>失败时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="failedTasksTable">
                                    <!-- 失败任务数据将通过JavaScript加载 -->
                                    <tr>
                                        <td colspan="7" class="text-center">加载中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="scheduled" role="tabpanel" aria-labelledby="scheduled-tab">
                        <!-- 计划任务表格，类似于上面的结构 -->
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>名称</th>
                                        <th>类型</th>
                                        <th>计划时间</th>
                                        <th>状态</th>
                                        <th>最后执行</th>
                                        <th>下次执行</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="scheduledTasksTable">
                                    <!-- 计划任务数据将通过JavaScript加载 -->
                                    <tr>
                                        <td colspan="7" class="text-center">加载中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 新建任务模态框 -->
<div class="modal fade" id="newTaskModal" tabindex="-1" aria-labelledby="newTaskModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="newTaskModalLabel">创建新任务</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="newTaskForm">
                    <div class="mb-3">
                        <label for="taskType" class="form-label">任务类型</label>
                        <select class="form-select" id="taskType">
                            <option selected disabled>选择任务类型...</option>
                            <optgroup label="股票数据">
                                <option value="stock_list">更新股票列表</option>
                                <option value="stock_daily">股票日线数据</option>
                                <option value="financial_statement">财务报表数据</option>
                                <option value="valuation">估值指标数据</option>
                            </optgroup>
                            <optgroup label="期货数据">
                                <option value="future_list">更新期货列表</option>
                                <option value="future_daily">期货日线数据</option>
                            </optgroup>
                            <optgroup label="ETF和基金">
                                <option value="etf_list">更新ETF列表</option>
                                <option value="etf_daily">ETF日线数据</option>
                                <option value="fund_list">更新基金列表</option>
                                <option value="fund_nav">基金净值数据</option>
                            </optgroup>
                            <optgroup label="加密货币">
                                <option value="crypto_list">更新加密货币列表</option>
                                <option value="crypto_daily">加密货币日线数据</option>
                            </optgroup>
                            <optgroup label="新闻和宏观数据">
                                <option value="financial_news">财经新闻</option>
                                <option value="macro_data">宏观经济数据</option>
                                <option value="stock_notice">股票公告</option>
                            </optgroup>
                        </select>
                    </div>
                    <div id="dynamicFields">
                        <!-- 动态字段将根据选择的任务类型生成 -->
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="submitTask">提交任务</button>
            </div>
        </div>
    </div>
</div>

<!-- 任务详情模态框 -->
<div class="modal fade" id="taskDetailModal" tabindex="-1" aria-labelledby="taskDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="taskDetailModalLabel">任务详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="taskDetailContent">
                <!-- 任务详情将通过JavaScript加载 -->
                <div class="text-center">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="retryTask">重试任务</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 当页面加载完成后初始化任务管理功能
document.addEventListener('DOMContentLoaded', function() {
    // 模拟任务数据，实际应用中应该通过API获取
    const mockTasks = [
        { id: 1, task_id: 'abcd1234', task_type: 'stock_daily', security_code: '600000', start_date: '2023-01-01', end_date: '2023-12-31', status: 'success', result_count: 252, create_time: '2023-12-15 08:30:45' },
        { id: 2, task_id: 'efgh5678', task_type: 'future_daily', security_code: 'IF2303', start_date: '2023-01-01', end_date: '2023-03-31', status: 'failed', result_count: 0, create_time: '2023-12-15 08:45:22', error_message: '连接超时' },
        { id: 3, task_id: 'ijkl9012', task_type: 'etf_daily', security_code: '510050', start_date: '2023-01-01', end_date: '2023-12-31', status: 'running', result_count: 156, create_time: '2023-12-15 09:10:05' },
        { id: 4, task_id: 'mnop3456', task_type: 'crypto_daily', security_code: 'BTC', start_date: '2023-01-01', end_date: '2023-12-31', status: 'pending', result_count: 0, create_time: '2023-12-15 09:20:18' },
        { id: 5, task_id: 'qrst7890', task_type: 'financial_news', security_code: null, start_date: null, end_date: null, status: 'success', result_count: 125, create_time: '2023-12-15 10:05:30' }
    ];
    
    // 填充所有任务表格
    const allTasksTable = document.getElementById('allTasksTable');
    allTasksTable.innerHTML = '';
    
    mockTasks.forEach(task => {
        const statusClass = {
            'success': 'text-success',
            'failed': 'text-danger',
            'running': 'text-primary',
            'pending': 'text-warning'
        }[task.status] || '';
        
        const statusIcon = {
            'success': 'fas fa-check-circle',
            'failed': 'fas fa-times-circle',
            'running': 'fas fa-spinner fa-spin',
            'pending': 'fas fa-clock'
        }[task.status] || 'fas fa-question-circle';
        
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${task.id}</td>
            <td>${task.task_type}</td>
            <td>${task.security_code || '-'}</td>
            <td>${task.start_date || '-'}</td>
            <td>${task.end_date || '-'}</td>
            <td><span class="${statusClass}"><i class="${statusIcon} me-1"></i>${task.status}</span></td>
            <td>${task.result_count}</td>
            <td>${task.create_time}</td>
            <td>
                <button class="btn btn-sm btn-info view-task" data-task-id="${task.id}">查看</button>
                ${task.status === 'failed' ? `<button class="btn btn-sm btn-warning retry-task" data-task-id="${task.id}">重试</button>` : ''}
                ${task.status === 'pending' ? `<button class="btn btn-sm btn-danger cancel-task" data-task-id="${task.id}">取消</button>` : ''}
            </td>
        `;
        allTasksTable.appendChild(row);
    });
    
    // 任务类型选择事件处理
    const taskTypeSelect = document.getElementById('taskType');
    const dynamicFields = document.getElementById('dynamicFields');
    
    taskTypeSelect.addEventListener('change', function() {
        const selectedType = this.value;
        dynamicFields.innerHTML = '';
        
        // 根据选择的任务类型生成不同的表单字段
        if (selectedType.includes('_daily') || selectedType.includes('_nav')) {
            // 需要证券代码和日期范围的任务类型
            dynamicFields.innerHTML = `
                <div class="mb-3">
                    <label for="securityCode" class="form-label">证券代码</label>
                    <input type="text" class="form-control" id="securityCode" placeholder="输入证券代码">
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="startDate" class="form-label">开始日期</label>
                        <input type="date" class="form-control" id="startDate">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="endDate" class="form-label">结束日期</label>
                        <input type="date" class="form-control" id="endDate">
                    </div>
                </div>
            `;
        } else if (selectedType.includes('_list')) {
            // 列表更新任务
            if (selectedType === 'stock_list') {
                dynamicFields.innerHTML = `
                    <div class="mb-3">
                        <label for="exchange" class="form-label">交易所</label>
                        <select class="form-select" id="exchange">
                            <option value="SSE">上海证券交易所</option>
                            <option value="SZSE">深圳证券交易所</option>
                            <option value="BSE">北京证券交易所</option>
                            <option value="ALL" selected>所有交易所</option>
                        </select>
                    </div>
                `;
            } else if (selectedType === 'future_list') {
                dynamicFields.innerHTML = `
                    <div class="mb-3">
                        <label for="exchange" class="form-label">交易所</label>
                        <select class="form-select" id="exchange">
                            <option value="CFFEX">中国金融期货交易所</option>
                            <option value="SHFE">上海期货交易所</option>
                            <option value="DCE">大连商品交易所</option>
                            <option value="CZCE">郑州商品交易所</option>
                            <option value="INE">上海国际能源交易中心</option>
                            <option value="ALL" selected>所有交易所</option>
                        </select>
                    </div>
                `;
            } else if (selectedType === 'fund_list') {
                dynamicFields.innerHTML = `
                    <div class="mb-3">
                        <label for="fundType" class="form-label">基金类型</label>
                        <select class="form-select" id="fundType">
                            <option value="stock">股票型</option>
                            <option value="bond">债券型</option>
                            <option value="mixed">混合型</option>
                            <option value="index">指数型</option>
                            <option value="etf">ETF</option>
                            <option value="lof">LOF</option>
                            <option value="all" selected>所有类型</option>
                        </select>
                    </div>
                `;
            }
        } else if (selectedType === 'financial_news') {
            dynamicFields.innerHTML = `
                <div class="mb-3">
                    <label for="newsSource" class="form-label">新闻来源</label>
                    <select class="form-select" id="newsSource">
                        <option value="sina">新浪财经</option>
                        <option value="eastmoney">东方财富</option>
                        <option value="10jqka">同花顺</option>
                        <option value="all" selected>所有来源</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="newsLimit" class="form-label">采集数量限制</label>
                    <input type="number" class="form-control" id="newsLimit" value="50" min="1" max="1000">
                </div>
            `;
        } else if (selectedType === 'stock_notice') {
            dynamicFields.innerHTML = `
                <div class="mb-3">
                    <label for="securityCode" class="form-label">股票代码</label>
                    <input type="text" class="form-control" id="securityCode" placeholder="输入股票代码">
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="startDate" class="form-label">开始日期</label>
                        <input type="date" class="form-control" id="startDate">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="endDate" class="form-label">结束日期</label>
                        <input type="date" class="form-control" id="endDate">
                    </div>
                </div>
            `;
        } else if (selectedType === 'macro_data') {
            dynamicFields.innerHTML = `
                <div class="mb-3">
                    <label for="indicator" class="form-label">经济指标</label>
                    <select class="form-select" id="indicator">
                        <option value="gdp">GDP</option>
                        <option value="cpi">CPI</option>
                        <option value="ppi">PPI</option>
                        <option value="unemployment">失业率</option>
                        <option value="interest_rate">利率</option>
                        <option value="forex_reserve">外汇储备</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="region" class="form-label">地区</label>
                    <select class="form-select" id="region">
                        <option value="中国" selected>中国</option>
                        <option value="美国">美国</option>
                        <option value="欧元区">欧元区</option>
                        <option value="日本">日本</option>
                    </select>
                </div>
            `;
        } else if (selectedType === 'financial_statement' || selectedType === 'valuation') {
            dynamicFields.innerHTML = `
                <div class="mb-3">
                    <label for="securityCode" class="form-label">股票代码</label>
                    <input type="text" class="form-control" id="securityCode" placeholder="输入股票代码">
                </div>
                ${selectedType === 'financial_statement' ? `
                <div class="mb-3">
                    <label for="reportType" class="form-label">报表类型</label>
                    <select class="form-select" id="reportType">
                        <option value="balance">资产负债表</option>
                        <option value="income">利润表</option>
                        <option value="cash_flow">现金流量表</option>
                        <option value="all" selected>所有报表</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="period" class="form-label">财报期间</label>
                    <select class="form-select" id="period">
                        <option value="年报">年报</option>
                        <option value="中报">中报</option>
                        <option value="一季报">一季报</option>
                        <option value="三季报">三季报</option>
                    </select>
                </div>
                ` : ''}
            `;
        }
    });
    
    // 提交新任务按钮事件处理
    document.getElementById('submitTask').addEventListener('click', function() {
        const taskType = document.getElementById('taskType').value;
        
        // 验证表单
        if (!taskType || taskType === '选择任务类型...') {
            alert('请选择任务类型');
            return;
        }
        
        // 在实际应用中，应该通过API提交任务
        alert('任务已提交');
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('newTaskModal'));
        modal.hide();
    });
    
    // 查看任务详情按钮事件处理
    document.querySelectorAll('.view-task').forEach(button => {
        button.addEventListener('click', function() {
            const taskId = this.getAttribute('data-task-id');
            const task = mockTasks.find(t => t.id == taskId);
            
            const detailContent = document.getElementById('taskDetailContent');
            
            // 显示任务详情
            detailContent.innerHTML = `
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>任务ID:</strong> ${task.task_id}</p>
                        <p><strong>任务类型:</strong> ${task.task_type}</p>
                        <p><strong>证券代码:</strong> ${task.security_code || '-'}</p>
                        <p><strong>状态:</strong> <span class="${{
                            'success': 'text-success',
                            'failed': 'text-danger',
                            'running': 'text-primary',
                            'pending': 'text-warning'
                        }[task.status] || ''}"><i class="${{
                            'success': 'fas fa-check-circle',
                            'failed': 'fas fa-times-circle',
                            'running': 'fas fa-spinner fa-spin',
                            'pending': 'fas fa-clock'
                        }[task.status] || 'fas fa-question-circle'} me-1"></i>${task.status}</span></p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>开始日期:</strong> ${task.start_date || '-'}</p>
                        <p><strong>结束日期:</strong> ${task.end_date || '-'}</p>
                        <p><strong>结果数量:</strong> ${task.result_count}</p>
                        <p><strong>创建时间:</strong> ${task.create_time}</p>
                    </div>
                </div>
                ${task.error_message ? `
                <div class="alert alert-danger mt-3">
                    <strong>错误信息:</strong> ${task.error_message}
                </div>
                ` : ''}
            `;
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('taskDetailModal'));
            modal.show();
            
            // 设置重试按钮状态
            const retryButton = document.getElementById('retryTask');
            if (task.status === 'failed') {
                retryButton.style.display = 'block';
                retryButton.setAttribute('data-task-id', task.id);
            } else {
                retryButton.style.display = 'none';
            }
        });
    });
    
    // 重试任务按钮事件处理
    document.getElementById('retryTask').addEventListener('click', function() {
        const taskId = this.getAttribute('data-task-id');
        
        // 在实际应用中，应该通过API重试任务
        alert(`重试任务 ${taskId}`);
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('taskDetailModal'));
        modal.hide();
    });
});
</script>
{% endblock %}